
# -*- coding: utf-8 -*-

import logging
import time
import os
import sys
import colorlog
from send_message import Send

SetLevel = "debug"

# 设置控制台打印的颜色
log_colors_config = {
    'DEBUG': 'yellow',
    'INFO': 'cyan',
    'WARNING': 'yellow',
    'ERROR': 'red',
    'CRITICAL': 'red',
}
class Log:
    def __init__(self):
        self.root_path = os.path.dirname(sys.executable) if getattr(sys, 'frozen', False) else os.path.dirname(
            os.path.abspath(__file__))
        self.logs_dir = os.path.join(self.root_path, 'logs')
        if not os.path.exists(self.logs_dir):
            os.makedirs(self.logs_dir)


    def __printconsole(self, level, message):
        logname = os.path.join(self.logs_dir, '{0}.log'.format(time.strftime('%Y-%m-%d')))
        # 创建一个logger
        logger = logging.getLogger()
        if SetLevel == 'debug':
            logger.setLevel(logging.DEBUG)
        elif SetLevel == 'info':
            logger.setLevel(logging.INFO)
        elif SetLevel == 'warn':
            logger.setLevel(logging.WARN)
        elif SetLevel == 'error':
            logger.setLevel(logging.ERROR)
        # 创建一个handler，用于写入日志文件
        fh = logging.FileHandler(logname, 'a', encoding='utf-8')
        # fh.setLevel(logging.DEBUG)
        # 再创建一个handler，用于输出到控制台
        ch = logging.StreamHandler()
        # ch.setLevel(logging.DEBUG)
        # 定义handler的输出格式
        formatter = colorlog.ColoredFormatter('%(log_color)s %(asctime)s - %(levelname)s - %(message)s',
                                              log_colors=log_colors_config)
        formatter1 = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
        fh.setFormatter(formatter1)
        ch.setFormatter(formatter)
        # 给logger添加handler
        logger.addHandler(fh)
        logger.addHandler(ch)
        # 记录一条日志
        if level == 'info':
            logger.info(message)
        elif level == 'debug':
            logger.debug(message)
        elif level == 'warning':
            logger.warning(message)
        elif level == 'error':
            logger.error(message)
        logger.removeHandler(ch)
        logger.removeHandler(fh)
        # 关闭打开的文件
        fh.close()

    def debug(self, message):
        self.__printconsole('debug', message)

    def info(self, message):
        self.__printconsole('info', message)

    def warning(self, message):
        self.__printconsole('warning', message)

    def error(self, message):
        self.__printconsole('error', message)
        Send.dingding(message)

if __name__ == '__main__':
    log = Log()
    log.debug('Debug message')
    log.info('Info message')
    log.warning('Warning message')
    log.error('Error message')
